// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function () {
    // 移动端菜单切换
    const navToggle = document.querySelector('.nav-toggle');
    const navMenu = document.querySelector('.nav-menu');

    if (navToggle && navMenu) {
        navToggle.addEventListener('click', () => {
            navMenu.classList.toggle('active');
        });
    }

    // API 测试功能
    const demoBtns = document.querySelectorAll('.demo-btn');
    const apiResult = document.getElementById('api-result');
    const copyBtn = document.querySelector('.copy-btn');

    // 复制功能
    if (copyBtn && apiResult) {
        copyBtn.addEventListener('click', async () => {
            try {
                await navigator.clipboard.writeText(apiResult.textContent);
                copyBtn.innerHTML = '<span>✅</span>';
                setTimeout(() => {
                    copyBtn.innerHTML = '<span>📋</span>';
                }, 2000);
            } catch (err) {
                console.error('复制失败:', err);
            }
        });
    }

    // API 测试按钮事件
    demoBtns.forEach(btn => {
        btn.addEventListener('click', async () => {
            // 移除所有active类
            demoBtns.forEach(b => b.classList.remove('active'));
            // 添加active类到当前按钮
            btn.classList.add('active');

            const apiUrl = btn.dataset.api;
            console.log(apiUrl)
            // 显示加载状态
            apiResult.innerHTML = `{
  "status": "loading",
  "message": "请求中...",
  "timestamp": ${Date.now()}
}`;

            try {
                const response = await fetch(apiUrl, {
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json'
                    }
                });

                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}`);
                }

                const data = await response.json();

                // 美化JSON显示
                apiResult.textContent = JSON.stringify(data, null, 2);

            } catch (error) {
                // 显示错误信息
                apiResult.innerHTML = `{
  "error": "请求失败",
  "message": "${error.message}",
  "url": "${apiUrl}",
  "timestamp": ${Date.now()}
}`;

                console.error('API请求失败:', error);
            }
        });
    });

    // 平滑滚动
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();

            const targetId = this.getAttribute('href');
            if (targetId === '#') return;

            const targetElement = document.querySelector(targetId);
            if (targetElement) {
                targetElement.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });

                // 关闭移动端菜单
                if (navMenu) {
                    navMenu.classList.remove('active');
                }
            }
        });
    });

    // 滚动显示导航栏阴影
    window.addEventListener('scroll', () => {
        const navbar = document.querySelector('.navbar');
        if (window.scrollY > 10) {
            navbar.style.boxShadow = '0 2px 20px rgba(0, 0, 0, 0.1)';
        } else {
            navbar.style.boxShadow = 'none';
        }
    });

    // 初始化页面时触发一次滚动事件
    window.dispatchEvent(new Event('scroll'));
});

// 简单的错误处理
window.addEventListener('error', (e) => {
    console.error('页面错误:', e.error);
});

// 未处理的Promise rejection
window.addEventListener('unhandledrejection', (e) => {
    console.error('未处理的Promise rejection:', e.reason);
    e.preventDefault();
});